#include "bsonobjeditordelegate.h"
#include <QtGui>
BSONObjEditorDelegate::BSONObjEditorDelegate(int durationColumn, QObject *parent)
: QItemDelegate(parent)
{
    this->durationColumn = 0;
}

void BSONObjEditorDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
        QString text = index.model()->data(index, Qt::DisplayRole).toString();

        QStyleOptionViewItem myOption = option;
        myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;

        drawDisplay(painter, myOption, myOption.rect, text);
        drawFocus(painter, myOption, myOption.rect);
    } else{
        QItemDelegate::paint(painter, option, index);
    }
}

QWidget *BSONObjEditorDelegate::createEditor(QWidget *parent,
        const QStyleOptionViewItem &option,
        const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
        QLineEdit *timeEdit = new QLineEdit(parent);
        connect(timeEdit, SIGNAL(editingFinished()),
                this, SLOT(commitAndCloseEditor()));
        return timeEdit;
    } else {
        return QItemDelegate::createEditor(parent, option, index);
    }
}

void BSONObjEditorDelegate::setEditorData(QWidget *editor,
                                  const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
       QString str = index.model()->data(index, Qt::DisplayRole).toString();
        QLineEdit *timeEdit = qobject_cast<QLineEdit *>(editor);
        timeEdit->setText(str);
    } else {
        QItemDelegate::setEditorData(editor, index);
    }
}

void BSONObjEditorDelegate::setModelData(QWidget *editor,
                                 QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
    if (index.column() == durationColumn) {
        QLineEdit *timeEdit = qobject_cast<QLineEdit *>(editor);
        QString str =timeEdit->text();
        model->setData(index, str);
    } else {
        QItemDelegate::setModelData(editor, model, index);
    }
}

void BSONObjEditorDelegate::commitAndCloseEditor()
{
    QTimeEdit *editor = qobject_cast<QTimeEdit *>(sender());
    emit commitData(editor);
    emit closeEditor(editor);
}

